package top.houry.im.server.handler.impl;

import cn.hutool.core.util.ObjectUtil;
import com.google.protobuf.TextFormat;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import top.houry.im.server.consts.ImServerMsgTypeConstants;
import top.houry.im.server.handler.ImServerMsgTypeHandler;
import top.houry.im.server.listener.ImServerNettyProcessorListener;
import top.houry.im.server.proto.ImMessage;
import top.houry.im.server.util.ImServerConnectionUtils;

@Slf4j
@Service(value = ImServerMsgTypeConstants.CLIENT_CHAT_MSG_FORWARD_REQ)
public class ImServeChatMsgForwardHandlerImpl implements ImServerMsgTypeHandler {
    @Override
    public void processImMsg(ImMessage.Server server, ChannelHandlerContext ctx) {
        try {
            ImMessage.ChatReqMessage  chatMsg = ImMessage.ChatReqMessage.parseFrom(server.getBytesData());
            log.info("[Req]-[ImServerLoginMsgHandlerImpl]-[processImMsg]-[params:{}]", TextFormat.printToUnicodeString(chatMsg));

            String fromUserId = chatMsg.getFromUserId();
            String toUserId = chatMsg.getToUserId();
            String msg = chatMsg.getChatMsg();
            String userName = chatMsg.getUserName();

            // TODO  校验好友关系

            ChannelHandlerContext handlerContext = ImServerConnectionUtils.getCtx(toUserId);
            if (ObjectUtil.isNull(handlerContext) || !handlerContext.channel().isActive()) {
                // TODO 保存数据库，或者消费队列
                return;
            }

            ImMessage.ChatRespMessage.Builder forwardMsg = ImMessage.ChatRespMessage.newBuilder();
            forwardMsg.setChatMsg(msg);
            forwardMsg.setFromUserId(fromUserId);
            forwardMsg.setToUserId(toUserId);
            forwardMsg.setUserName(userName);


            ImMessage.Server.Builder resp = ImMessage.Server.newBuilder();
            resp.setMsgType(ImServerMsgTypeConstants.SERVER_CHAT_MSG_FORWARD_RESP);
            resp.setBytesData(forwardMsg.build().toByteString());
            resp.setCode(200);
            resp.setMsgTip("ok");

            handlerContext.writeAndFlush(resp).addListener(new ImServerNettyProcessorListener("消息转发"));


        } catch (Exception e) {
            log.info("[Exception]-[ImServerLoginMsgHandlerImpl]-[processImMsg]", e);
        }
    }
}
